// 快速OCR测试
const quickOcrTest = {
  async test() {
    console.log('开始快速OCR测试...');
    
    // 获取Token
    const token = await this.getToken();
    if (!token) {
      console.error('获取Token失败');
      return;
    }
    
    console.log('Token获取成功:', token.substring(0, 20) + '...');
    
    // 测试OCR
    try {
      const result = await this.testOCR(token);
      console.log('OCR测试结果:', result);
    } catch (error) {
      console.error('OCR测试失败:', error);
    }
  },

  async getToken() {
    const config = require('../config/api.js');
    
    // 使用密码认证方式
    const tokenRequest = {
      auth: {
        identity: {
          methods: ['password'],
          password: {
            user: {
              name: 'ilieyun',
              password: 'Lieyun@2090',
              domain: {
                name: 'ilieyun'
              }
            }
          }
        },
        scope: {
          project: {
            name: 'cn-north-4'
          }
        }
      }
    };

    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens',
        method: 'POST',
        header: {
          'Content-Type': 'application/json'
        },
        data: tokenRequest,
        success: (res) => {
          console.log('Token响应状态码:', res.statusCode);
          console.log('Token响应头:', res.header);
          
          if (res.statusCode === 201 && res.header['X-Subject-Token']) {
            resolve(res.header['X-Subject-Token']);
          } else {
            reject(new Error('获取Token失败: ' + res.statusCode));
          }
        },
        fail: (error) => {
          reject(new Error('Token请求失败: ' + error.errMsg));
        }
      });
    });
  },

  async testOCR(token) {
    const config = require('../config/api.js');
    
    // 简单的测试图片数据
    const imageData = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
    
    const ocrRequest = {
      image: imageData
    };

    return new Promise((resolve, reject) => {
      wx.request({
        url: `https://ocr.cn-north-4.myhuaweicloud.com/v2/${config.ocr.huawei.projectId}/ocr/general-text`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'X-Auth-Token': token
        },
        data: ocrRequest,
        success: (res) => {
          console.log('OCR响应状态码:', res.statusCode);
          console.log('OCR响应数据:', res.data);
          
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            reject(new Error('OCR请求失败: ' + res.statusCode));
          }
        },
        fail: (error) => {
          reject(new Error('OCR请求失败: ' + error.errMsg));
        }
      });
    });
  }
};

module.exports = quickOcrTest;
